import random
import string
from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .serializers import *
from rest_framework.permissions import IsAuthenticated
from .models import *
from utils.permission import TeacherPermission
from rest_framework.status import HTTP_404_NOT_FOUND,HTTP_201_CREATED
from django.contrib.auth.models import Group
from celery_tasks.emial.tasks import send_email_task
# Create your views here.


class ClassesViewSet(ModelViewSet):
    queryset = Classes.objects.filter(is_delete=False)# 接口操作对的使用数据
    serializer_class = ClassesSerializer
    permission_classes = [TeacherPermission]

    def get_serializer(self,*args,**kwargs):
        # 重写get_serializer获取数据方法，根据不同的操作显示不同的序列化器
        if self.action == 'students':
            return CreateUserializer(*args,**kwargs)#返回学生序列化器
        return self.serializer_class(*args,**kwargs)#返回班级序列化器

    @action(methods=['post'] ,detail=True)
    def students(self,request,pk):
        #获取班级
        try:
            classes = self.get_queryset().get(id=pk)
        except Classes.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        #得到前段传入的数据
        username = request.data['username']
        email = request.data['email']
        first_name = request.data['first_name']

        # 判断该用户是否已经在改班级，查询班级使用成员，以用户作为条件
        member = classes.member.filter(username=username)
        #如果在，返回提示已存在
        if member:
            return Response({'msg':'该成员已经加入该班级'})
        # 如果不在，则判断用户是否存在，判断是否是新学员
        user = User.objects.filter(username=username)
        if user:
            user = user.first()
            #如果存在，将该用户添加到班级，并返回
            classes.member.add(user)
            return Response(CreateUserializer.bata)


        #如果是新学员，使用序列化器，进行反序列化，效验传入进来的数据
        user_serializer = self.get_serializer(data=request.data)
        user_serializer.is_valid(raise_exception=True)
        user = User(username=username,first_name=first_name,email=email)
        #生成初始密码
        source = string.ascii_letters + string.digits
        password = ''.join(random.sample(source,6))
        user.set_password(password)#给用户设置密码，会进行加密，储存密文
        user.save()

        #发送邮件
        # print(email,username,first_name,classes.name)

        #设置学生身份
        group = Group.objects.get(id=2)
        group.user_set.add(user)

        #添加到对应班级
        classes.member.add(user)

        #生成邮件发送异步任务
        send_email_task.delay(email,username,password,classes.name)

        #返回
        return Response(user_serializer.data,status=HTTP_201_CREATED)
